# Pre-Scheme Makefile

CC=gcc
FORMAT=clang-format -i
PRESCHEME=prescheme

CFLAGS=-O2 -g -Wall
CFLAGS+=$(shell pkg-config --cflags prescheme)
LDLIBS+=$(shell pkg-config --libs prescheme)

SDL2_CFLAGS=$(shell pkg-config --cflags sdl2)
SDL2_LDLIBS=$(shell pkg-config --libs sdl2)

SOURCES= packages.scm \
         lib/ps-string.scm \
         lib/ps-vector.scm \
         lib/ps-utils.scm \
         lib/ps-grid.scm \
         lib/ps-sdl2.scm

TARGETS= hello \
         append \
         vecfun \
         recfun \
         btree \
         game-of-life \
         prime-sum

all: $(TARGETS)

%.c: %.scm $(SOURCES)
	rm -f $@
	( echo ",batch"; \
	  echo "(prescheme-compiler '$* '(\"packages.scm\") 'ps-init \"$@\""; \
	  echo " '(header \"#include \\\"include/ps-init.h\\\"\")"; \
	  echo " '(copy (ps-vector vector-unfold1))"; \
	  echo " '(copy (ps-vector vector-unfold2))"; \
	  echo " '(copy (ps-vector vector-unfold3))"; \
	  echo " '(copy (ps-vector vector-fold1))"; \
	  echo " '(copy (ps-vector vector-fold2))"; \
	  echo " '(copy (ps-vector vector-fold3))"; \
	  echo " '(copy (ps-vector vector-map1!))"; \
	  echo " '(copy (ps-vector vector-map2!))"; \
	  echo " '(copy (ps-vector vector-map3!))"; \
	  echo " '(copy (ps-vector vector-map1))"; \
	  echo " '(copy (ps-vector vector-map2))"; \
	  echo " '(copy (ps-vector vector-map3))"; \
	  echo " '(copy (ps-vector vector-for-each1))"; \
	  echo " '(copy (ps-vector vector-for-each2))"; \
	  echo " '(copy (ps-vector vector-for-each3))"; \
	  echo " '(copy (ps-vector vector-fill!))"; \
	  echo ")"; \
	  echo ",exit" ) \
	| $(PRESCHEME)
	$(FORMAT) $@

game-of-life.c: game-of-life.scm $(SOURCES)
	rm -f $@
	( echo ",batch"; \
	  echo "(prescheme-compiler '$* '(\"packages.scm\") 'ps-init \"$@\""; \
	  echo " '(header \"#include \\\"include/ps-init.h\\\"\")"; \
	  echo " '(header \"#include \\\"include/ps-sdl2.h\\\"\")"; \
	  echo " '(header \"#include <time.h>\")"; \
	  echo " '(copy (ps-grid grid-index))"; \
	  echo " '(copy (ps-grid grid-fold))"; \
	  echo " '(copy (ps-grid grid-for-each))"; \
	  echo " '(copy (ps-grid grid-update!))"; \
	  echo " '(copy (ps-grid grid-unfold))"; \
	  echo ")"; \
	  echo ",exit" ) \
	| $(PRESCHEME)
	$(FORMAT) $@

game-of-life.o: game-of-life.c
	$(CC) $(CPPFLAGS) $(CFLAGS) $(SDL2_CFLAGS) -c $^ -o $@

game-of-life: game-of-life.o
	$(CC) $(LDFLAGS) $^ $(LDLIBS) $(SDL2_LDLIBS) -o $@

clean:
	rm -f $(TARGETS)
	rm -f $(TARGETS:=.o)
	rm -f $(TARGETS:=.c)

.PRECIOUS: $(TARGETS:=.c)
.INTERMEDIATE: game-of-life.o

.PHONY: all clean
